from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QHeaderView, QAbstractItemView, QTableWidgetItem, QMessageBox

from opsql import rootOp


class MRt():
    def __init__(self):
        self.ui = QUiLoader().load('view/机房类别管理.ui')
        self.inittable()
        self.ui.searchBtn.clicked.connect(self.inittable)
        self.ui.addBtn.clicked.connect(self.add)
        self.ui.modifyBtn.clicked.connect(self.modify)
        self.ui.deleteBtn.clicked.connect(self.delete)


    def inittable(self):
        name = self.ui.nameIn.text()
        result = rootOp.searchrt(name)
        row = 0
        if result:
            row = len(result)
        self.ui.tableWidget.setRowCount(row)
        self.ui.tableWidget.setColumnCount(1)
        self.ui.tableWidget.setHorizontalHeaderLabels(['机房类别'])
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.tableWidget.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.ui.tableWidget.verticalHeader().setVisible(False)
        self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)

        for i in range(row):
            for j in range(1):
                data = QTableWidgetItem(str(result[i][j]))
                self.ui.tableWidget.setItem(i, j, data)


    def add(self):
        name = self.ui.nameShow.text()
        if name == '':
            QMessageBox.warning(self.ui, '提示', '请输入电脑类别')
            return
        result = rootOp.addrt(name)
        if result:
            QMessageBox.information(self.ui, '提示', '添加成功')
            self.inittable()
        else:
            QMessageBox.warning(self.ui, '提示', '添加失败')

    def modify(self):
        row = self.ui.tableWidget.currentRow()
        if row == -1:
            QMessageBox.warning(self.ui, '提示', '请选择电脑类别')
            return
        oldname = self.ui.tableWidget.item(row, 0).text()
        newname = self.ui.nameShow.text()
        result = rootOp.modifyrt(oldname,newname)
        if result:
            QMessageBox.information(self.ui, '提示', '修改成功')
            self.inittable()
        else:
            QMessageBox.warning(self.ui, '提示', '修改失败')

    def delete(self):
        row = self.ui.tableWidget.currentRow()
        if row == -1:
            QMessageBox.warning(self.ui, '提示', '请选择订单')
            return
        name = self.ui.tableWidget.item(row, 0).text()
        result = rootOp.deletert(name)
        if result:
            QMessageBox.information(self.ui, '提示', '删除成功')
            self.inittable()
        else:
            QMessageBox.warning(self.ui, '提示', '删除失败')